package auth

import (
	"context"
	"fmt"
	"github.com/asim/go-micro/v3"
	"github.com/gin-gonic/gin"
	"net/http"
	"server/proto/user"
	"server/utils"
)


// Github godoc
//	@Summary		Github
//	@Description	Github第三方快捷登陆
//	@Tags			Auth2
//	@Accept			json
//	@Produce		json
//	@Param			code    query     string  false  "code"  Format(code)
//	@Success		200		{object}  model.LoginResponse
//	@Failure		500		{object}  model.LoginResponse
//	@Router			/oauth/github [get]
func Github(ctx *gin.Context) {
	//获取code
	code := ctx.Query("code")

	service := micro.NewService()

	moduleService := user.NewUserModuleService("develop_user", service.Client())

	rep,err:= moduleService.GithubUserAuth(context.TODO(), &user.UserAuthRequest{Token: code})
	if err != nil {
		ctx.Redirect(http.StatusMovedPermanently,"http://127.0.0.1:8080/login")
		ctx.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "获取用户信息失败",
		})
		return
	}
	if rep.Code == 200 { //获取认证成功
		token, _ := utils.GenToken(rep.Username, utils.FrontUserExpireDuration, utils.FrontUserSecretKey)
		address := fmt.Sprintf("http://127.0.0.1:8080/index?username=%s&token=%s", rep.Username, token)
		ctx.Redirect(http.StatusMovedPermanently, address)
	} else {
		ctx.Redirect(http.StatusMovedPermanently, "http://127.0.0.1:8080/login")
	}
}
